//Load common code that includes config, then load the app logic for this page.
//将表单序列化成json格式的数据(但不适用于含有控件的表单，例如复选框、多选的select)
(function($) {
	$.fn.serializeJson = function() {
		var jsonData1 = {};
		var serializeArray = this.serializeArray();
		// 先转换成{"id": ["12","14"], "name": ["aaa","bbb"],
		// "pwd":["pwd1","pwd2"]}这种形式
		$(serializeArray).each(
				function() {
					if (jsonData1[this.name]) {
						if ($.isArray(jsonData1[this.name])) {
							jsonData1[this.name].push(this.value);
						} else {
							jsonData1[this.name] = [ jsonData1[this.name],
									this.value ];
						}
					} else {
						jsonData1[this.name] = this.value;
					}
				});
		// 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name":
		// "bb", "pwd":"pwd2"}]的形式
		var vCount = 0;
		// 计算json内部的数组最大长度
		for ( var item in jsonData1) {
			var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
			vCount = (tmp > vCount) ? tmp : vCount;
		}

		if (vCount > 1) {
			var jsonData2 = new Array();
			for (var i = 0; i < vCount; i++) {
				var jsonObj = {};
				for ( var item in jsonData1) {
					jsonObj[item] = jsonData1[item][i];
				}
				jsonData2.push(jsonObj);
			}
			return JSON.stringify(jsonData2);
		} else {
			return "[" + JSON.stringify(jsonData1) + "]";
		}
	};
})(jQuery);
var initDatepicker = function() {
	$(".input-datepicker").datepicker({
		"dateFormat" : "yy-mm-dd"
	});
}
var submitPiplineResult = function() {
	var jsonStr = $("#pipelinePublicForm").serializeJson();
	$.ajax({
		url : "/client/pipelineResult.htm",
		type : "POST",
		contentType : 'application/json;charset=utf-8', // 设置请求头信息
		dataType : "json",
		data : jsonStr,
		success : function(data) {
			window.location.href = "/client/pipelineList.htm";
		},
		error : function(res) {
			alert("提交失败，刷新页面重新提交");
			window.location.reload();
		}
	});
};
var changProvince = function(obj) {
	var provinceId = obj.options[obj.selectedIndex].value;
	$.ajax({
		type : "GET",
		contentType : 'application/json',
		url : "/api/" + provinceId + "/city",
		success : function(response) {
			var html = '';
			$.each(response, function(i, item) {
				html = html + '<option value="' + item.id + '">'
						+ item.cityName + '</option>';
			})
			$("#tcity").html(html);
		}
	});
};
var changPurchaseOrganization = function(obj) {
	var purchaseOrganizationId = obj.options[obj.selectedIndex].value;
	$.ajax({
		type : "POST",
		cache : false,
		dataType : 'json',
		url : "/client/getPurchaseOrganizationUser.htm",
		data : {
			'purchaseOrganizationId' : purchaseOrganizationId
		},
		success : function(response, textStatus, jqXHR) {
			if (response.resCode == '0000') {
				var html = '';
				$.each(response.content, function(i, item) {
					html = html + '<option value="' + item.tUser.id + '">'
							+ item.tUser.realName + '</option>';
				})
				$("#responsorUserId").html(html);
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.info("response>>>>>", errorThrown);
		}
	});
};
var submitContractForm = function(type) {
	var startTime = $("#startTime").val();
	if (!startTime) {
		alert("请选择合同起始时间！");
		return;
	}
	var expiredTime = $("#expiredTime").val();
	if (!expiredTime) {
		alert("请选择合同过期时间！");
		return;
	}
	if (startTime > expiredTime) {
		alert("合同起始时间必须小于过期时间！");
		return;
	}
	var purchaseOrderDesc = $("#purchaseOrderDesc").val();
	if (!purchaseOrderDesc) {
		alert("订单描述不能为空！");
		return;
	}
	var purchaseOrga = $("#purchaseOrga").val();
	if (purchaseOrga < 0) {
		alert("请选择有效采购组！");
		return;
	}
	var provinceId = $("#provinceId").val();
	if (provinceId < 0 || !provinceId) {
		alert("请选择有效省份！");
		return;
	}
	var tcity = $("#tcity").val();
	if (!tcity || tcity < 0) {
		alert("请选择有效城市！");
		return;
	}
	var address = $("#address").val();
	if (!address) {
		alert("请输入详细地址！");
		return;
	}
	var responsorUserId = $("#responsorUserId").val();
	if (responsorUserId < 0) {
		alert("请选择合同负责人！");
		return;
	}
	var price = $("#price").val();
	if (!price) {
		alert("请输入合同总金额！");
		return;
	}
	$("#contract_form_submit_type").attr("value", type);
	$("#form_create_contract").submit();
};
var openEditPurchaseOrderPayment = function(obj, purOrderPaymentId, displayNo) {
	$("tr").filter(".edit-tr-wrap").next().remove();
	$("tr").filter(".edit-tr-wrap").removeClass("edit-tr-wrap").removeAttr(
			"style").find("td a:first-child").show().next().hide();
	if (!purOrderPaymentId) {// 新增order payment
		$(obj).hide().next().show().parent().parent().addClass("edit-tr-wrap")
				.css({
					"border-left-width" : "4px",
					"border-left-style" : "solid",
					"border-left-color" : "rgb(255, 155, 66)"
				}).after(
						$("#purchaseOrderPaymentTemplate").tmpl(
								{
									"planAmount" : "0",
									"billedAmount" : "0",
									"increamentTax" : "0",
									"amountWithoutTax" : "0",
									"orderPaymentRemark" : $(
											"#orderPaymentRemark_" + displayNo)
											.html(),
									"displayOrderNo" : displayNo,
									"purchaseOrderId" : $('#purchaseOrderId')
											.val(),
									"percentage" : "0",
									"currency" : $('#currency').val()
								}));
		initDatepicker();
		return;
	}
	$
			.ajax({
				type : "POST",
				cache : false,
				dataType : 'json',
				url : "/client/getPurchaseOrderPayment.htm",
				data : {
					'orderPaymentId' : purOrderPaymentId
				},
				success : function(data, textStatus, jqXHR) {
					if (data.resCode == '0000') {
						var orderPayment = data.content;
						orderPayment.displayOrderNo = displayNo;
						orderPayment.purchaseOrderId = $('#purchaseOrderId')
								.val();
						orderPayment.currency = $('#currency').val();
						$(obj).hide().next().show().parent().parent().addClass(
								"edit-tr-wrap").css({
							"border-left-width" : "4px",
							"border-left-style" : "solid",
							"border-left-color" : "rgb(255, 155, 66)"
						}).after(
								$("#purchaseOrderPaymentTemplate").tmpl(
										orderPayment));
						initDatepicker();
					}
				},
				error : function(jqXHR, textStatus, errorThrown) {
					console.info("response>>>>>", errorThrown);
					alert("服务端异常！");
				}
			});
};
var closeEditPurchaseOrderPayment = function(obj) {
	if (obj) {
		$(obj).hide().prev().show().parent().parent().removeClass(
				"edit-tr-wrap").removeAttr("style");
	} else {
		var trObj = $(".edit-tr-wrap").removeClass("edit-tr-wrap").removeAttr(
				"style").find("td a");
		var length = trObj.length;
		if (length > 2) {
			trObj.first().next().hide();
		} else {
			trObj.last().hide();
		}
		trObj.first().show();
	}
	$("#purOrderPaymentTemplateTr").remove();
};
var deletePurchaseOrderPayment = function(obj) {
	if ($(".purchaseOrderPaymentClass").children("tr[class!='edit-tr']").length == 1) {
		alert("请至少保留一个里程碑。");
		return;
	}
	var cTd = $(obj).parent();
	var cTr = cTd.parent();
	if (cTr.hasClass("edit-tr-wrap")) {
		cTr.next().remove();
	}
	if (cTr.prev().length == 0) {
		var cTdNext = cTd.next();
		cTr.next().append(cTdNext);
	}
	cTr.remove();
};
var modifyPurchaseOrderPayment = function() {
	var jsonStr = $("#editPurchaseOrderPayment").serializeJson();
	$
			.ajax({
				url : "/client/createOrder.htm",
				type : "POST",
				contentType : 'application/json;charset=utf-8', // 设置请求头信息
				dataType : "json",
				data : jsonStr,
				success : function(data) {
					if (data.resCode == '0000') {
						var orderPayment = data.content;
						orderPayment.currency = $("#currency").val();
						orderPayment.totalPlanAmount = parseInt(orderPayment.planAmount);
						$(
								"td[id!='planAmount_"
										+ orderPayment.displayOrderNo
										+ "'][id^='planAmount_']").each(
								function(index, e) {
									orderPayment.totalPlanAmount += parseInt($(
											this).html().substr(1));
								});
						//
						if (orderPayment.displayOrderNo == 1) {
							orderPayment.price = $("#price").val();
						} else {
							$("#totalPlanAmount").html(
									$("#currency").val()
											+ orderPayment.totalPlanAmount);
						}
						$(".edit-tr-wrap").replaceWith(
								$("#purchaseOrderPaymentItem").tmpl(
										orderPayment));
						$("#purOrderPaymentTemplateTr").remove();
					} else {
						alert(data.resMsg);
					}
				},
				error : function(res) {
					console.info("res>>>>>", res);
					alert("服务器端异常！");
				}
			});
};
// //////////////////////////////////////////////////////////////////////////////////////////////
var addClientMaterial = function(obj, itemNo) {
	var materialName = prompt("请输入新商品名称");
	if (!materialName) {
		return;
	}
	$.ajax({
		url : "/client/addClientMaterial.htm",
		type : "POST",
		contentType : 'application/json;charset=utf-8', // 设置请求头信息
		dataType : "json",
		data : "{\"materialName\":\"" + materialName + "\"}",
		success : function(data) {
			if (data.resCode == '0000') {
				var material = data.content;
				$(
						"<option value=\"" + material.id
								+ "\" selected=\"selected\">"
								+ material.materialName + "</option>")
						.appendTo($(obj).prev());
				$(
						"<option value=\"" + material.id + "\">"
								+ material.materialName + "</option>")
						.appendTo(
								$(".purchaseOrderItemClass").find(
										"select[name='materialId'][id!='materialId_"
												+ itemNo + "']"));
			} else {
				alert(data.resMsg);
			}
		},
		error : function(res) {
			console.info("res>>>>>", res);
			alert("服务器端异常！");
		}
	});
};
var addPurchaseOrderItem = function() {
	var lastTr = $(".purchaseOrderItemClass").children("tr:last-child");
	if (lastTr.length == 0) {
		return;
	}
	// purchaseOrderId
	var purchaseOrderId = lastTr.children("input[name='purchaseOrderId']")
			.val();
	// orderItemNo
	var orderItemNo = lastTr.children("input[name='orderItemNo']").val();
	// materials
	var materialArray = new Array();
	lastTr.find("select[name='materialId'] option").each(function(index, e) {
		materialArray.push({
			"materialId" : $(e).val(),
			"materialName" : $(e).html()
		});
	});
	var materials = $.parseJSON(JSON.stringify(materialArray));
	// units
	var unitArray = new Array();
	lastTr.find("select[name='unitId'] option").each(function(index, e) {
		unitArray.push({
			"unitId" : $(e).val(),
			"unitName" : $(e).html()
		});
	});
	var units = $.parseJSON(JSON.stringify(unitArray));
	//
	lastTr.after($("#purchaseOrderItemTemplate").tmpl({
		"purchaseOrderId" : purchaseOrderId,
		"orderItemNo" : parseInt(orderItemNo, 10) + 1,
		"materials" : materials,
		"units" : units
	}));
	initDatepicker();
};
var delPurchaseOrderItem = function() {
	var checkBox = $(".purchaseOrderItemClass").find(":checkbox");
	var checkedBox = checkBox.filter(":checked");
	if (checkedBox.length == 0) {
		alert("请勾选要删除的商品条目！");
		return;
	}
	if (checkBox.length == checkedBox.length) {
		alert("请至少保留一条商品条目！");
		return;
	}
	checkedBox.parent().parent().remove();
};
var purchaseOrderItemsFlag = true;
var submitPurchaseOrderItems = function() {
	if(!purchaseOrderItemsFlag){
		return ;
	}
	purchaseOrderItemsFlag = false;
	var jsonStr = $("#purchaseOrderItemForm").serializeJson();
	$.ajax({
		url : "/client/addPurchaseOrderItems.htm",
		type : "POST",
		contentType : 'application/json;charset=utf-8', // 设置请求头信息
		dataType : "json",
		data : jsonStr,
		success : function(data) {
			if (data.resCode == '0000') {
				window.location.href = "/client/pipelineList.htm?purchaseOrderId="+$("#purchaseOrderId").val();
			} else {
				alert(data.resMsg);
			}
			purchaseOrderItemsFlag = true;
		},
		error : function(res) {
			console.log(res);
			alert("服务器端异常！");
		}
	});
};